package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.dialog.SelectCityDialog;
import com.shwread.android.ui.dialog.SelectCityListener;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.lang.reflect.Type;

import logic.bean.Area;
import logic.bean.UserAddressInfo;
import logic.constants.DefaultConsts;
import logic.util.Utils;


/**
 * 收货地址编辑
 * 
 * @author xuzhijun
 * @date 2015年3月17日
 */
public class AddressInfoEditActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener,
        SelectCityListener
{
	private Context              context;
	private TextView             tvTitle;
	private Button               btnHome;
	private Button               btnBack;
	
	private EditText             tvName;
	private EditText             tvPhone;
	private EditText             tvAddress;
	private TextView             tvLocation;
	private UserAddressInfo      addressInfo;
	private int                  TAG_FROM;
	private Button               btnSubmit;
	private long                 addressId;
	private int                  areaAddressId;
	private boolean              isDefaultAddress;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.address_info_edit);
		context = this;
		initView();
		setListener();
		
		Bundle bundle = getIntent().getExtras();
		if (bundle != null)
		{
			TAG_FROM = bundle.getInt(DefaultConsts.EDIT_ADDRESS_FROM_TYPE);
			
			if (TAG_FROM == DefaultConsts.EDIT_ADDRESS_UPDATE_TAG)
			{
				addressInfo = (UserAddressInfo) bundle.getSerializable(DefaultConsts.EDIT_ADDRESS_UPDATEINFO);
				initData();
			}
			else if (TAG_FROM == DefaultConsts.EDIT_ADDRESS_ADD_TAG)
			{
				setEmptyData();
			}
		}
	}
	
	@Override
	public Handler getUIHandler() {
		// TODO Auto-generated method stub
		return null;
	}
	
	private void initView() {
		//Title
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		tvTitle.setText(getResources().getString(R.string.address_title));
		btnHome = (Button) findViewById(R.id.common_header_home);
		btnHome.setVisibility(View.VISIBLE);
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		
		tvName = (EditText) findViewById(R.id.address_info_edit_name);
		tvName.setSelection(tvName.getText().toString().length());
		tvPhone = (EditText) findViewById(R.id.address_info_edit_phone);
		tvLocation = (TextView) findViewById(R.id.address_info_edit_location);
		tvAddress = (EditText) findViewById(R.id.address_info_edit_address);
		btnSubmit = (Button) findViewById(R.id.address_info_edit_submit_but);
	}
	
	private void setListener() {
		btnHome.setOnClickListener(this);
		btnBack.setOnClickListener(this);
		btnSubmit.setOnClickListener(this);
		tvLocation.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_home:
				//				Utils.ToastShow(AddressInfoEditActivity.this, "点击了返回主页");
				//				startActivity(new Intent(AddressInfoEditActivity.this, MainActivity.class));
				BaseSimpleActivity.gotoMainActivity();
				break;
			case R.id.common_header_back:
				AddressInfoEditActivity.this.finish();
				break;
			case R.id.address_info_edit_submit_but:
				submitAddress();
				break;
			case R.id.address_info_edit_location:
				SelectCityDialog dialog = null;
				if (null == addressInfo)
				{
					dialog = new SelectCityDialog(context);
				}
				else
				{
					dialog = new SelectCityDialog(context, addressInfo.getProviceId(), addressInfo.getCityId(), addressInfo.getAreaAddressId());
				}
				if (dialog.hasData() && !dialog.isShowing())
				{
					dialog.setListener(this);
					dialog.show();
				}
				else
				{
					Utils.showToast(context, "暂无城市数据");
				}
				break;
			default:
				break;
		}
		
	}
	
	/**
	 * 填充数据
	 */
	private void initData() {
		if (addressInfo != null)
		{
			tvName.setText(Utils.isEmpty(addressInfo.getName()) ? "" : addressInfo.getName());
			tvPhone.setText(Utils.isEmpty(addressInfo.getPhone()) ? "" : addressInfo.getPhone());
			String str = addressInfo.getProvinceName() + addressInfo.getCityName() + addressInfo.getAreaName();
			tvLocation.setText(Utils.isEmpty(str) ? "" : str);
			tvAddress.setText(Utils.isEmpty(addressInfo.getDetailAddress()) ? "" : addressInfo.getDetailAddress());
			addressId = addressInfo.getAddressId();
			areaAddressId = addressInfo.getAreaAddressId();
			isDefaultAddress = addressInfo.isDefault();
			
		}
		
	}
	
	private void setEmptyData() {
		tvName.setText("");
		tvPhone.setText("");
		tvLocation.setText("");
		tvAddress.setText("");
	}
	
	/**
	 * 提交信息时，需要提前获取修改后的信息
	 */
	private void submitAddress() {
		String name = tvName.getText().toString();
		String phone = tvPhone.getText().toString();
		String detailAddress = tvAddress.getText().toString();
		String location = tvLocation.getText().toString();
		
		if (Utils.isEmpty(name))
		{
			Utils.showToast(context, "收货人姓名不能为空");
		}
		else if (Utils.isEmpty(phone))
		{
			Utils.showToast(context, "手机号码不能为空");
		}
		else if (!Utils.isMobile(phone))
		{
			Utils.showToast(context, "请输入正确的手机号");
		}
		else if (Utils.isEmpty(location))
		{
			Utils.showToast(context, "请选择所在地区");
		}
		else if (Utils.isEmpty(detailAddress))
		{
			Utils.showToast(context, "详细地址不能为空");
		}
		else
		{
			//提交 请求
			if (TAG_FROM == DefaultConsts.EDIT_ADDRESS_UPDATE_TAG)
			{
				//修改地址
				
				ActionHelp.updateUserDeliveryAddress(context, addressId, isDefaultAddress, name, phone, (int) areaAddressId, detailAddress, new updateAddressAction());
				
			}
			else if (TAG_FROM == DefaultConsts.EDIT_ADDRESS_ADD_TAG)
			{
				//新增加地址
				ActionHelp.addUserDeliveryAddress(context, name, phone, areaAddressId, detailAddress, "", new addAddressAction());
			}
		}
		
	}
	
	/**
	 * 修改收货地址 监听事件
	 */
	private class updateAddressAction
	        extends
	        ObjectHttpResponseHandler<Object>
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			Logger.e(throwable);
			if (statusCode < 1000)
			{
				
				Utils.ToastShow(context, "网络错误");
			}
			else
			{
				Utils.ToastShow(context, "请求出错");
			}
			
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, Object object, String responseString) {
			Logger.i(responseString);
			System.out.println("xxxxxxxxxxxxxxxxxxx_" + responseString);
			Utils.showToast(context, "修改成功");
			Intent returnIntent = new Intent();
			addressInfo.setDetailAddress(tvAddress.getText().toString());
			returnIntent.putExtra(DefaultConsts.ADDRESS_LIST, addressInfo);
			setResult(RESULT_OK, returnIntent);
			AddressInfoEditActivity.this.finish();
		}
		
		@Override
		public Type getType() {
			return new TypeToken<Object>()
			{
			}.getType();
		}
		
	}
	
	/**
	 * 增加收货地址 监听事件
	 */
	private class addAddressAction
	        extends
	        ObjectHttpResponseHandler<Object>
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			Logger.e(throwable);
			if (statusCode < 1000)
			{
				
				Utils.ToastShow(context, "网络错误");
			}
			else
			{
				Utils.ToastShow(context, "请求出错");
			}
			
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, Object object, String responseString) {
			Logger.i(responseString);
			System.out.println("xxxxxxxxxxxxxxxxxxx_" + responseString);
			Utils.showToast(context, "添加成功");
			Intent returnIntent = getIntent();
			int zz = returnIntent.getExtras().getInt(DefaultConsts.EDIT_ADDRESS_FROM_CONFIEM_ORDER);
			if (zz == DefaultConsts.EDIT_ADDRESS_DEFAULT_ADD_TAG)
			{
				setResult(DefaultConsts.EDIT_ADDRESS_ADD_OK_N, returnIntent);
				AddressInfoEditActivity.this.finish();
			}
			else
			{
				AddressInfoEditActivity.this.finish();
				setResult(DefaultConsts.EDIT_ADDRESS_ADD_OK_RESULT);
			}
			
		}
		
		@Override
		public Type getType() {
			return new TypeToken<Object>()
			{
			}.getType();
		}
		
	}
	
	@Override
	public void finish(Area province, Area city, Area area) {
		if (province != null && city != null /* && area!=null */)
		{
			if (area == null)
			{
				areaAddressId = -1;
				tvLocation.setText(province.areaName + city.areaName);
			}
			else
			{
				areaAddressId = area.id;
				tvLocation.setText(province.areaName + city.areaName + area.areaName);
			}
		}
		
	}
	
}
